package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class IdService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public Long getPublishId(String type,String objectId){
        // 转换成全大写
        type = StringUtils.upperCase(type);

        // 设置key,避免重复覆盖值
        String hashKey = "TANHUA_ID_HASH_" + type;
        // 查看redis中是否有key,有则返回,无则继续
        if (redisTemplate.opsForHash().hasKey(hashKey,objectId)) {
            return Long.valueOf(redisTemplate.opsForHash().get(hashKey,objectId).toString());
        }

        // 使用redis完成自增长id
        String idKey = "" + type;
        Long pId = redisTemplate.opsForValue().increment(idKey);

        // 保存到hashKey中,下次再进行查询可以在上面直接返回
        redisTemplate.opsForHash().put(hashKey,objectId,pId.toString());

        return pId;
    }
}
